package cn.ainit.sys.yzpe;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.hibernate.SQLQuery;
import org.junit.Test;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import cn.ainit.sys.common.dao.SysBaseDao;

@Transactional
@Repository
public class YzpeDaoImpl extends SysBaseDao implements YzpeDao {
	
	
	/**
	 * 
	 */
	@Override
	public YzpeReturnObj calculate(YzpeReceiveObj receiveObj) throws Exception {
		//ring 
		//执行存储过程      参数说明：(?,?,?,?,?,a?,b?,c?) 
		//最后叁个参数为输出参数 result; expStr; expStr2; 
		YzpeReturnObj returnObj = new YzpeReturnObj();
		String funcCode = receiveObj.getFuncCode();
		Map<String, Object> paramMap = receiveObj.getParamMap();
		Connection conn= null;
		CallableStatement cs = null;
		int paramCount = 0;
		try {
			conn = this.getJdbcTemplate().getDataSource().getConnection();
			//查找数据库存储过程名
			String funcSql = " SELECT FUNC_CODE,FUNC_NAME FROM SYS_EXPRESSION_FUNC_MAP WHERE FUNC_CODE='"+receiveObj.getFuncCode()+"'";
			List<Map<String, Object>> funcList = this.getJdbcTemplate().queryForList(funcSql);
			if (funcList == null) {
				System.out.println("表：SYS_EXPRESSION_FUNC_MAP 需要配置 ");
				throw new RuntimeException("没有找到方法，请到表");
			}else {
				if (funcList.size() > 1) {
					throw new RuntimeException("配置的方法超过两个，请正确配置");
				}
			}
			
			String[] tmpKey = sortKey(receiveObj.getParamMap().keySet().toArray()); // 将key排序，按顺序传入
			paramCount = tmpKey.length;
			StringBuffer procName = new StringBuffer("{Call "+funcList.get(0).get("FUNC_NAME")+"(");
			for (int i = 0; i < paramCount; i++) {
				procName.append("?,");
			}
			procName.append("?,?,?,?)}");//叁个输出参数
			cs = conn.prepareCall(procName.toString());
			for(int i = 0; i < paramCount; i++){
				cs.setString(i+1,paramMap.get(tmpKey[i])==null?"":paramMap.get(tmpKey[i]).toString());
			}
			cs.registerOutParameter(paramCount+1, Types.VARCHAR);//msg
			cs.registerOutParameter(paramCount+2, Types.VARCHAR);//公式
			cs.registerOutParameter(paramCount+3, Types.VARCHAR);//数值
			cs.registerOutParameter(paramCount+4, Types.VARCHAR);//数值 sql语句
			
			cs.executeQuery();
			returnObj.setMsg(cs.getString(paramCount+1));
			returnObj.setExpStr(cs.getString(paramCount+2));
			returnObj.setResult(cs.getString(paramCount+3));
			if ( cs.getString(paramCount+4) != null && cs.getString(paramCount+4).indexOf("select") >= 0 ) {
				returnObj.setParamMap(this.getJdbcTemplate().queryForList(cs.getString(paramCount+4)));
			}
			
			if(returnObj.getMsg() == null || "".equals(returnObj.getMsg())){
				returnObj.setMsg("success");
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}finally{
			if (cs!= null) {
				cs.close();
			}
			if (conn != null) {
				conn.close();
			}
		}
		return returnObj;
	}
	
	
	//排序键值
	public String[]  sortKey(Object[] keys){
		String[] tmReObj = new String[keys.length];
		for(int i = 0; i < keys.length ;i++){
			tmReObj[i] = keys[i] == null?"":keys[i].toString();
		}
		return tmReObj;
	}
	//添加版印次
	@Override
	public String newPiciFunc(String djId,
			List<Map<String, String>> allObjList,String uid) throws Exception {
		List<Object[]> list =  new ArrayList<Object[]>();
		Connection conn = null;
		CallableStatement cs = null;
		String flagStr = ""; 
		try {
			conn =  this.getJdbcTemplate().getDataSource().getConnection();
			String sql = " INSERT INTO BS_MULTILINES(ID,PARAM1,PARAM4,PARAM2,PARAM3,PARAM5,SOURCE_ID) VALUES (SYS_GUID(),?,?,?,'"+djId+"',?,'1')";
			if(allObjList.size() >0){
				for (int i = 0; i < allObjList.size(); i++) {
					if(i==0){
						list.add(new Object[]{allObjList.get(i).get("YINCHANG").toString(),Integer.parseInt(allObjList.get(i).get("YINSHU")),allObjList.get(i).get("zxr").toString(),"1"});
					}else {
						list.add(new Object[]{allObjList.get(i).get("YINCHANG").toString(),Integer.parseInt(allObjList.get(i).get("YINSHU")),allObjList.get(i).get("zxr").toString(),"0"});
					}
				}
				int[] inLeng= this.jdbcTemplate.batchUpdate(sql, list);
				if (inLeng.length == allObjList.size()) {
//					flagStr = "success";
					//调用过程
					String sql1 = "{Call pk_yz_print_explain.up_ysfydNewPiciSure(?,?,?)}";
					cs = conn.prepareCall(sql1);
					cs.setString(1,djId);
					cs.setString(2,uid);
					cs.registerOutParameter(3, Types.VARCHAR);
					cs.execute();
					conn.commit();
					flagStr = cs.getString(3);
				}else {
					flagStr = "false";
				} 
			}else{
				flagStr = "error";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if (cs != null) {
				cs.close();
			}
			if (conn != null) {
				conn.close();
			}
		}
		return flagStr;
	}
	@Override
	public String judgePiciFunc(String peId, String uid, String dsId)
			throws Exception {
		String returnStr = "";
		Connection conn = null;
		CallableStatement cs = null;
		try {
			conn =  this.getJdbcTemplate().getDataSource().getConnection();
			String sql ="{Call pk_yz_print_explain.up_ysfydNewPici(?,?,?,?,?)}";
			cs = conn.prepareCall(sql);
			cs.setString(1,peId);
			cs.setString(2,dsId);
			cs.setString(3,uid);
			cs.setString(4,"");
			cs.registerOutParameter(5,Types.VARCHAR);
			cs.execute();
			conn.commit();
			returnStr = cs.getString(5);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if (cs != null) {
				cs.close();
			}
			if (conn != null) {
				conn.close();
			}
		}
		return returnStr;
	}
	
	@Override
	public String queryZRR(String sql) {
		Map<String, Object> map= getJdbcTemplate().queryForMap(sql);	
		if(map!=null){
			return map.get("USER_ID").toString();
		} 
		return null;
	}
	
	
}
